<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="quoteOrderPage"
        uniqueId="quoteOrderTable"
      ></ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      :isShowBackBtn="false"
      :isShowSubmitBtn="false"
      :isShowCancelBtn="false"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :visible.sync="visible"
      :title="title"
      size="95%"
    >
      <el-row type="flex" class="row-bg" justify="end">
        <el-button type="primary" icon="el-icon-download" @click="exportRepairList()">明细项导出</el-button>
        <el-button type="primary" @click="handleSubmit({...formDataDialog,submitType:0})">保存</el-button>
        <el-button type="primary" @click="handleSubmit({...formDataDialog,submitType:1})">提交</el-button>
      </el-row>
    </ele-form-drawer>
    <el-dialog title="图片"
               :visible.sync="picVIsible"
               width="95%"
               class="abow_dialog"
               :append-to-body="true"
               v-loading="isLoading"
               :close-on-click-modal="false">
      <div
        class="item"
        v-for="(item, key) in imgUrlList"
        :key="key"
      >
        <el-image
          style="width: 100px; height: 100px"
          :src="item"
          :preview-src-list="imgUrlList">
        </el-image>
        <!--        <el-image-->
        <!--          :src="item"-->
        <!--        ></el-image>-->
      </div>
    </el-dialog>
    <dialogRepairTable ref="dialogRepairTable" @responseList="responseRepairList" />
  </div>
</template>

<script>
import {operateList, searchConfig, rowConfig, exportExlUrl} from './config'

import {
  quoteConfirmUpdate,
  quoteOrderCreate,
  quoteOrderDeleteById,
  quoteOrderGetById,
  quoteOrderPage,
  quoteOrderUpdate
} from '@/api/quote/order'
import { formDescDialogMixin } from '@/views/quote/order/config'
import dialogRepairTable from '@/views/repair/ele-dialog-table/index'
import {exportExcel, uniqueKey} from '@/utils/judge'

export default {
  name: 'quoteOrder',
  components: { dialogRepairTable },
  mixins: [searchConfig, formDescDialogMixin],
  data() {
    const self = this
    return {
      imgUrlList:[],
      picVIsible : false,
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      repairSelectAll:false,
      extraSelectAll:false,
      formDataDialog: {},
      // formDescDialog, //新增修改框
      operateList,
      quoteOrderPage,
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection',
          fixed: 'left'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'orderCode',
          label: '订单编号',
          showOverflowTooltip: true
        },
        {
          prop: 'modelName',
          label: '车型',
          showOverflowTooltip: true
        },
        {
          prop: 'vinCode',
          label: 'vin码',
          showOverflowTooltip: true
        },
        {
          prop: 'uwbCode',
          label: 'uwb码',
          showOverflowTooltip: true
        },
        {
          prop: 'vehicleRegisterDate',
          label: '首次上牌时间',
        },
        {
          prop: 'vehicleGuidePrice',
          label: '新车指导价',
        },
        {
          prop: 'quoteHours',
          label: '工时费用(元)',
          showOverflowTooltip: true
        },
        {
          prop: 'quoteItems',
          label: '配件费用(元)',
          showOverflowTooltip: true
        },
        {
          prop: 'quoteExtra',
          label: '固定费用(元)',
          showOverflowTooltip: true
        },
        {
          prop: 'quoteTotal',
          label: '总价(元)',
          showOverflowTooltip: true
        },
        // {
        //   prop: 'quoteState1',
        //   label: '报价单状态',
        //   render: (h, scope) => {
        //     if (scope.row.quoteState === '0') {
        //       return (
        //         <el-tag color="#ccc" effect="dark" size="medium">
        //           {'草稿'}
        //         </el-tag>
        //       )
        //     } else if (scope.row.quoteState === '1') {
        //       return (
        //         <el-tag color="skyblue" effect="dark" size="medium">
        //           {'推送'}
        //         </el-tag>
        //       )
        //     }  else if (scope.row.quoteState === '2') {
        //       return (
        //         <el-tag color="green" effect="dark" size="medium">
        //           {'确认'}
        //         </el-tag>
        //       )
        //     } else if (scope.row.quoteState === '-1') {
        //       return (
        //         <el-tag color="#ccc" effect="dark" size="medium">
        //           {'未创建'}
        //         </el-tag>
        //       )
        //     }
        //   },
        //   showOverflowTooltip: true
        // },
        {
          prop: 'quoteState2',
          label: '推送状态',
          render: (h, scope) => {
            if (scope.row.repairPushCount + scope.row.extraPushCount === 0) {
              return (
                <el-tag color="#ccc" effect="dark" size="medium">
                  {'未推送'}
                </el-tag>
              )
            } else if (scope.row.repairPushCount + scope.row.extraPushCount > 0 && scope.row.repairPushCount + scope.row.extraPushCount < scope.row.repairCount + scope.row.extraCount) {
              return (
                <el-tag color="skyblue" effect="dark" size="medium">
                  {'部分推送'}
                </el-tag>
              )
            } else if (scope.row.repairPushCount + scope.row.extraPushCount === scope.row.repairCount + scope.row.extraCount) {
              return (
                <el-tag color="green" effect="dark" size="medium">
                  {'全部推送'}
                </el-tag>
              )
            }
          },
          showOverflowTooltip: true
        },
        {
          prop: 'quoteState3',
          label: '确认状态',
          render: (h, scope) => {
            if (scope.row.confimCount === 0) {
              return (
                <el-tag color="#ccc" effect="dark" size="medium">
                  {'未确认'}
                </el-tag>
              )
            } else if (scope.row.confimCount > 0 && scope.row.confimCount +scope.row.extraPushCount < scope.row.repairCount  + scope.row.extraCount)  {
              return (
                <el-tag color="skyblue" effect="dark" size="medium">
                  {'部分确认'}
                </el-tag>
              )
            } else if (scope.row.confimCount + scope.row.extraPushCount === scope.row.repairCount + scope.row.extraCount ) {
              return (
                <el-tag color="green" effect="dark" size="medium">
                  {'全部确认'}
                </el-tag>
              )
            }
          },
          showOverflowTooltip: true
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 160,
          fixed: 'right',
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            )
          }
        }
      ]
    }
  },
  computed: {},
  methods: {
    responseRepairList(data) {
      let newData = []
      data.forEach((val) => {
        const item = {
          repairId: val.id,
          repairItem: val.repairItem,
          repairQuote: val.repairHoursTotalPrice,
          itemName: val.repairMaterialName
        }
        newData.push(item)
      })

      let list = [...(this.formDataDialog?.repairList ?? []), ...newData.map((ite) => ite)]
      // 筛选重复值,插入
      this.$set(this.formDataDialog, 'repairList', uniqueKey(list, 'repairItem'))
    },
    responseExtraList(data) {
      console.log(data)
      let newData = []
      data.forEach((val) => {
        const item = {
          extraId: val.id,
          extraName: val.description
        }
        newData.push(item)
      })
      let list = [...(this.formDataDialog?.extraList ?? []), ...newData.map((ite) => ite)]
      // 筛选重复值,插入
      this.$set(this.formDataDialog, 'extraList', uniqueKey(list, 'extraName'))
    },
    addRepairList() {
      this.$refs.dialogRepairTable.mixinDialogVisible = true
    },
    updateTotalitem() {
      let item = 0;
      this.formDataDialog.repairList.forEach((val) => {
        item += val.itemQuote
      })
      this.formDataDialog.quoteItems = item
    },
    updateTotalhour() {
      let hour = 0;
      this.formDataDialog.repairList.forEach((val) => {
        hour += val.repairQuote
      })
      this.formDataDialog.quoteHours = hour
    },
    updateTotalextra() {
      let extra = 0;
      this.formDataDialog.extraList.forEach((val) => {
        extra += Number(val.extraQuote)
      })
      this.formDataDialog.quoteExtra = extra
    },
    updateExtraList() {
      this.formDataDialog.extraList.forEach((element) => {
        if(element.isPushOg !== 'Y')
        {
          let temp = this.formDataDialog.estPrice * element.extraQuoteRate * element.extraQuoteCoef  / 10000
          element.extraQuote = temp.toFixed(2)
        }
      });
      this.updateTotalextra()
    },
    doRepairSelectAll() {
      this.repairSelectAll = !this.repairSelectAll
      this.formDataDialog.repairList.forEach((val) => {
        if(val.isPushOg !== 'Y')
        {
          if(this.repairSelectAll)
          {
            val.isPush = 'Y'
          }
          else
          {
            val.isPush = 'N'
          }
        }
      })
    },
    doExtraSelectAll() {
      this.extraSelectAll = !this.extraSelectAll
      this.formDataDialog.extraList.forEach((val) => {
        if(val.isPushOg !== 'Y')
        {
          if(this.extraSelectAll)
          {
            val.isPush = 'Y'
          }
          else
          {
            val.isPush = 'N'
          }
        }
      })
    },
    exportRepairList() {
      console.warn(this.formDataDialog.repairList)
      //## 数据处理
      let mainStr = [];
      //一级表
      mainStr.push("维修项目\n")
      let mainTitle = ["部件","部件描述","维修项目","工时报价(元)","物料名称","物料状态","物料数量","领用单位","成本价","加成价","物料报价(元)"];//一级标题
      let mainTitleForKey = ["partsName","descConcat","repairItem","repairQuote","itemName","state","itemCount","countUnitShow","unitPrice","unitPriceJc","itemQuote"];//一级过滤
      let mainList = this.formDataDialog.repairList ;//一级数据
      mainStr.push(mainTitle.join(",")+"\n");   //标题添加上换列转成字符串并存进数组
      for(let i=0;i<mainList.length;i++){
        let temp = [];
        for(let j=0;j<mainTitleForKey.length;j++){
          temp.push(mainList[i][mainTitleForKey[j]]); //根据过滤器拿出对应的值
        }
        mainStr.push(temp.join(",")+"\n");    //取出来的值加上逗号换列转字符串存数组
      }
      mainStr.push("\n\n固定项目\n")
      let mainTitle2 = ["项目名称","系数(%)","费率(%)","价格(元)"];//一级标题
      let mainTitleForKey2 = ["extraName","extraQuoteCoef","extraQuoteRate","extraQuote"];//一级过滤
      let mainList2 = this.formDataDialog.extraList ;//一级数据
      mainStr.push(mainTitle2.join(",")+"\n");   //标题添加上换列转成字符串并存进数组
      for(let i=0;i<mainList2.length;i++){
        let temp2 = [];
        for(let j=0;j<mainTitleForKey2.length;j++){
          temp2.push(mainList2[i][mainTitleForKey2[j]]); //根据过滤器拿出对应的值
        }
        mainStr.push(temp2.join(",")+"\n");    //取出来的值加上逗号换列转字符串存数组
      }
      // console.log(JSON.stringify(mainStr.join("")));//打印文本

      //两个表数组转成字符串合并
      let merged = mainStr.join("")
      //console.log(JSON.stringify(merged));//打印结果

      //## 导出操作
      // encodeURIComponent解决中文乱码
      const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(merged)
      // 通过创建a标签实现
      let link = document.createElement('a')
      link.href = uri
      // 对下载的文件命名
      link.download = `报价明细项目.csv`
      document.body.appendChild(link)
      link.click()
    },
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        add: () => {
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm('此操作将删除所选数据及关联明细数据, 是否继续?', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.mmcId).join(',')
            this.rowDel(ids)
          })
        }
      }
      fnc[data.handleName]()
    },
    viewPic(url) {
      if(url)
      {
        this.imgUrlList = url.split(",");
        this.picVIsible = true;
      }
      else
      {
        this.$message.warning("所选数据没有保存图片")
      }
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        exportExl: () => {
          console.log('导出触发' + row.mmcId)
          this.exportEXl(row.mmcId)
        },
        edit: () => {
          console.warn(row.haveUnpush)
          // if (row.haveUnpush !== '1' && row.quoteState !== '-1') {
          //   this.$message.warning('已全部推送的数据不可编辑' || '提示')
          // } else {
          //
          // }
          quoteOrderGetById(row.mmcId).then((res) => {
            this.formDataDialog = res.data.result
            if(!this.formDataDialog.estPrice)
            {
              this.formDataDialog.estPrice = 0
            }
          })

          this.visible = true
        },
        print: () => {
          if (row.quoteState === '-1') {
            this.$message.warning('未创建的数据无法预览打印' || '提示')
          }
          else
          {
            this.$router.push({
              path: '/quote/order/orderPrint',
              query: {
                id: row.mmcId
              }
            })
          }
        },
        delete: () => {
          this.$confirm('此操作将删除该数据及关联明细数据, 是否继续?', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.mmcId)
          })
        }
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 弹框提交事件
    handleSubmit(data) {
      // 判断状态 submitProdAreaList
      if (this.isLoading) return
      //必填项校验
      if(!this.formDataDialog.customerName)
      {
        this.$message.warning("客户名称不能为空")
        return;
      }
      if(!this.formDataDialog.repairList || this.formDataDialog.repairList.length === 0 )
      {
        this.$message.warning("维修项目费用不能为空")
        return;
      }
      else
      {
        for (let i = 0; i < this.formDataDialog.repairList.length; i++) {
          if(!this.formDataDialog.repairList[i].repairItem && this.formDataDialog.repairList[i].isPush==='Y' && this.formDataDialog.repairList[i].isPushOg === 'N' )
          {
            this.$message.warning("维修项目费用第"+(i+1)+"行：维修项目不能为空")
          }
          if(this.formDataDialog.repairList[i].repairQuote == null  && this.formDataDialog.repairList[i].isPush==='Y' && this.formDataDialog.repairList[i].isPushOg === 'N')
          {
            this.$message.warning("维修项目费用第"+(i+1)+"行：工时报价不能为空")
            return;
          }
          if(this.formDataDialog.repairList[i].itemCount == null  && this.formDataDialog.repairList[i].isPush==='Y' && this.formDataDialog.repairList[i].isPushOg === 'N')
          {
            this.$message.warning("维修项目费用第"+(i+1)+"行：部件数量不能为空，如无需部件请输入0")
            return;
          }
          if(this.formDataDialog.repairList[i].itemQuote == null  && this.formDataDialog.repairList[i].isPush==='Y' && this.formDataDialog.repairList[i].isPushOg === 'N' )
          {
            this.$message.warning("维修项目费用第"+(i+1)+"行：部件报价不能为空，如无需部件请输入0")
            return;
          }
        }
      }
      if(!this.formDataDialog.extraList  || this.formDataDialog.extraList.length === 0 )
      {
        this.$message.warning("固定收费项目不能为空")
        return;
      }
      else
      {
        for (let i = 0; i < this.formDataDialog.extraList.length; i++) {
          if(this.formDataDialog.extraList[i].extraQuoteCoef == null )
          {
            this.$message.warning("固定收费项目第"+(i+1)+"行：项目系数不能为空")
          }
          if(this.formDataDialog.extraList[i].extraQuoteRate == null )
          {
            this.$message.warning("固定收费项目第"+(i+1)+"行：项目费率不能为空")
            return;
          }
          if(this.formDataDialog.extraList[i].extraQuote == null )
          {
            this.$message.warning("固定收费项目第"+(i+1)+"行：项目报价不能为空")
            return;
          }
        }
      }

      if(data.submitType === 0)
      {
        const params =
          this.formDataDialog.quoteState === '-1'
            ? {
              title: "保存成功",
              api: quoteOrderCreate,
              data
            }
            : {
              title: "保存成功",
              api: quoteOrderUpdate,
              data
            }
        console.log(params)
        this.doSubmit(params)
      }
      else
      {

        this.$confirm(
          "该操作无法撤回，请确实是否提交",
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            type: "warning",
          }
        ).then(() => {

          let pushCount = 0
          this.formDataDialog.repairList.forEach((item) => {
            if(item.isPush==='Y' && item.isPushOg === 'N')
            {
              pushCount++
            }
          });
          this.formDataDialog.extraList.forEach((item) => {
            if(item.isPush==='Y' && item.isPushOg === 'N')
            {
              pushCount++
            }
          });
          if(pushCount === 0)
          {
            this.$message.warning("提交时至少需要选择一条数据")
            return;
          }
          const params =
            this.formDataDialog.quoteState === '-1'
              ? {
                title: "提交成功",
                api: quoteOrderCreate,
                data
              }
              : {
                title: "提交成功",
                api: quoteOrderUpdate,
                data
              }
          console.log(params)
          this.doSubmit(params)
        });
      }
    },
    // 删除
    rowDel(data) {
      this.loading = true
      quoteOrderDeleteById(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    exportEXl(data) {
      exportExcel(exportExlUrl + data)
    },
    // 刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    }
  }
}
</script>
